package structures.review.stack;

import java.util.Stack;

public class CalculatorDemo {
    public static void main(String[] args) {
        // 1+((2+3)×4)-5 --> 1 2 3 + 4 × + 5 –
        String expression = "1 2 3 + 4 * + 5 -";
        System.out.println(postfixExpression(expression));
    }

//    private static String toPostfixExpression(String express) {
//        byte[] expressBytes = express.getBytes();
//        Stack<Byte> signStack = new Stack<>();
//        Stack<Byte> tempStack = new Stack<>();
//
//        for (byte data : expressBytes) {
//
//        }
//    }

    private static int postfixExpression(String express) {
        String[] dataArray = express.split(" ");
        Stack<String> numStack = new Stack<>();
        for (String data : dataArray) {
            if (data.matches("\\d+")) {
                numStack.push(data);
                continue;
            }
            int ret = 0;
            int num1 = Integer.parseInt(numStack.pop());
            int num2 = Integer.parseInt(numStack.pop());
            switch (data) {
                case "+":
                    ret = num1 + num2;
                    break;
                case "-":
                    ret = num2 - num1;
                    break;
                case "*":
                    ret = num1 * num2;
                    break;
                case "/":
                    ret = num2 / num1;
                    break;
                default:
                    System.out.println("运算符匹配错误");
            }
            numStack.push(String.valueOf(ret));

        }
        return Integer.parseInt(numStack.pop());
    }
}
